<template>
  <a-card>
    <template #title>
      <BackButton />
    </template>
    <a-form>
      <a-form-item ref="name" label="类别名称" name="name" v-bind="validateInfos.name">
        <a-input v-model:value="formModel.name" placeholder="请输入类别名称" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 14, offset: 1 }">
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
        <a-button style="margin-left: 10px" @click="resetFields">重置</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>
<script>
import { onMounted, reactive } from "vue";
import { useForm } from "@ant-design-vue/use";
import { useRoute } from "vue-router";
import { categoryCfg, addCategoryCfg, updateCategoryCfg } from "@/api/category.conf";
import { useService } from "@/utils/request";
export default {
  setup() {
    const route = useRoute();
    const categoryRequest = useService(categoryCfg);
    const addCategoryRequest = useService(addCategoryCfg);
    const updateCategoryRequest = useService(updateCategoryCfg);

    const formModel = reactive({
      name: "",
    });

    //编辑ID
    let editCategoryId = null;
    onMounted(() => {
      const { id } = route.params;

      if (id) {
        editCategoryId = id;
        
        categoryRequest
          .setEndPath(id)
          .reload()
          .then((response) => {
            const res = response.data || [];
            formModel.name = (res[0] || {}).name;
          });
      } else {
        formModel.name = "";
      }
    });

    const rules = {
      name: [
        { required: true, message: "请输入类别名称", trigger: "blur" },
        { min: 1, max: 8, message: "最多输入1到8个字符", trigger: "blur" },
      ],
    };

    const { resetFields, validate, validateInfos } = useForm(formModel, rules);

    const onSubmit = () => {
      validate()
        .then(() => {
          //修改一个分类
          if (editCategoryId) {
            updateCategoryRequest
              .setEndPath(editCategoryId)
              .setData(formModel)
              .reload(true);
            return;
          }
          //新增分类
          addCategoryRequest.setData(formModel).reload(true);
        })
        .catch((error) => {
          console.log("error", error);
          return;
        });
    };

    return {
      onSubmit,
      formModel,
      rules,
      resetFields,
      validateInfos,
    };
  },
};
</script>
